class UsersMatch < ActiveRecord::Base
  belongs_to :user
  belongs_to :match
  serialize :stocks, Hash
    
     def getQuote(s)
          url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22#{s}%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="
          resp = Net::HTTP.get_response(URI.parse(url))
          data = resp.body
          json = ActiveSupport::JSON.decode(data)
          quote = json["query"]["results"]["quote"]
          return nil if quote["PreviousClose"] == nil
          
          #must determine change status
          if quote["Change"] == "0.00" 
               change = "nochange"
          elsif /(\+|-)/.match(quote["Change"])[0] == "+"
               change = "gain"
          else
               change = "loss"
          end
          
          {
               :previousClose => (quote['PreviousClose'].to_f*100).to_i,
               :name => quote["Name"],
               :symbol => quote["symbol"],
               :price => (quote['LastTradePriceOnly'].to_f*100).to_i,
               :change => change
          }
     end


     def changeStock(sym, qty, price)
          sym.upcase!
          
          if self.stocks[sym] == nil then
               self.stocks[sym] = {'price' => price, 'shares' => qty}
          else
               self.money += self.stocks[sym]['price']*self.stocks[sym]['shares']
               self.stocks[sym]['shares'] += qty
               self.stocks[sym]['price'] = price
          end
          
          
          self.money -= self.stocks[sym]['price']*self.stocks[sym]['shares']
          self.stocks.delete sym if self.stocks[sym]['shares'] == 0
     end

     def updateCapital
          if self.last_fetched + 60*60 > Time.now and self.capital != nil then
               return
          end
         
          self.last_fetched = Time.now
          c = self.money
          pc= self.money
          
          self.stocks.each do |sym, h|
               quote = self.getQuote(sym)
               self.stocks.delete(sym) if quote == nil
               next if quote == nil
               h['price'] = quote[:price]
               h['previousClose']=quote[:previousClose]
               pc += h['previousClose'] * h['shares']
               c += h['price'] * h['shares']
          end
          
          self.capital = c
          
          if pc < c
               change = "gain"
          elsif pc > c
               change = "loss"
          else
               change = "nochange"
          end
          
          self.change = change
          self.last_quoted = Time.now
          self.save
     end

     def user
          User.find_by_id(self.user_id)
     end

end
